/* Copyright 2009 Anthony Surma
This file is part of Java's Kademlia Extension (JKADX).

JKADX is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.

JKADX is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with JKADX.  If not, see <http://www.gnu.org/licenses/>.
 */

package jkadx.networking;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class SocketController
{    
    private final NetworkingInterface p2papplication;
    private final UDPSocketServer udpserver;
    private final UDPSocketClient udpclient;  
    private final ExecutorService threadPool = Executors.newSingleThreadExecutor();
 
    public SocketController(final NetworkingInterface p2papplication,final int incomingport, final int outgoingport)
            throws SocketException
    {        
        this.p2papplication  = p2papplication;
        this.udpserver       = new UDPSocketServer(this, incomingport, 1432);
        this.udpclient       = new UDPSocketClient(this, outgoingport);
        threadPool.execute(udpserver);       
    }

    public void sendPacket(final byte[] payload, final InetAddress address, final int port) 
            throws IOException
    {	
	udpclient.send(payload, address, port);
    }

    public void sendPacket(final byte[] payload, final InetAddress address, final int port, final int length)
            throws IOException
    {
	udpclient.send(payload, address, port, length);
    }

    void received(final DatagramPacket packet)
    {
	p2papplication.processIncoming(packet);
    }
        
    public void closeSockets()
    {
        try 
        {
            udpserver.closeSocket();           
        } catch (InterruptedException ex) {}
        threadPool.shutdown();
    }
}